import 'dart:convert';

import 'package:aj_flutter_appsp_push/aj_flutter_appsp_push.dart';
import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'message_display_second_page.dart';
import 'notification_message_model.dart';
import 'payload_model.dart';

class MessageDisplayPage extends StatefulWidget {
  MessageDisplayPage({Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new _MessageDisplayPageState();
  }
}

class _MessageDisplayPageState extends State<MessageDisplayPage> {
  String _result = 'getPayloadResult';
  AudioCache audioCache = AudioCache();
  static OverlayEntry entry;
  NotificationMessageModel model;
  AjFlutterAppspPush pushPlugin = new AjFlutterAppspPush();

  @override
  void initState() {
    super.initState();
    _initPlugin();
  }

  _initPlugin() async {
    try {
      pushPlugin.getMessageArrivedCallback((result) {
        print('getMessageArrivedCallback getResult ${result}');
        setState(() {
          _result = result;
        });
        _convertMessageToModel();
      });
    } on PlatformException {
      print('PlatformException');
    }

    try {
      pushPlugin.getMessageClickCallback((result) {
        print('getMessageClickCallback getResult ${result}');
        setState(() {
          _result = result;
        });
        _convertMessageToModel();
      });
    } on PlatformException {
      print('PlatformException');
    }
  }

  //弹出对话框
  _showaAlertDialog(NotificationMessageModel model) {
    entry?.remove();
    entry = null;
    entry = OverlayEntry(builder: (context) {
      return AlertDialog(
        title: Text(
          model.title ?? "",
          style: TextStyle(color: Color(0xFF333333)),
        ),
        content: Text(
          model.content ?? "",
          style: TextStyle(color: Color(0xFF333333)),
        ),
        actions: <Widget>[
          TextButton(
              child: Text(
                '取消',
                style: TextStyle(color: Color(0xFF5b74FF)),
              ),
              onPressed: () {
                entry?.remove();
                entry = null;
              }),
          TextButton(
              child: Text(
                  '确定',
                  style: TextStyle(color: Color(0xFF5b74FF)),
                 ),
              onPressed: () {
                entry?.remove();
                entry = null;
              })
        ],
      );
    });
    Overlay.of(context).insert(entry);
  }

  ///把透传消息子串转成对象
  _convertMessageToModel() {
    print('_convertMessageToModel _result $_result');
    NotificationMessageModel model = NotificationMessageModel.fromJson(json.decode(_result));
    String soundName = json.encode(model.notificationExtras);
    soundName = soundName.replaceAll("\\", "");
    soundName = soundName.replaceAll("\"{", "{");
    soundName = soundName.replaceAll("}\"", "}");
    if (soundName != null &&
        soundName.isNotEmpty && soundName != "{}") {
      PayloadModel payloadModel = PayloadModel.fromJson(json.decode(soundName));
      print('payloadModel.sound ${payloadModel.sound}');
      String music =  payloadModel.sound ?? "";
      if (music.isNotEmpty) {
        audioCache.play((payloadModel.sound ?? "") + '.mp3',
            mode: PlayerMode.LOW_LATENCY);
      }
    }

    print('_convertMessageToModel model $model');
    _showaAlertDialog(model);
  }

  @override
  Widget build(BuildContext context) {
    print("MessageDisplayPage build ");
    return Scaffold(
        body: Center(
            child: InkWell(
              child: Text('当前是演示页面，点击跳转到新页面'),
              onTap: () {
                Navigator.of(context).push(MaterialPageRoute(
                  builder: (context) {
                    return MessageDisplaySecondPage();
                  },
                ));
              },
            )));
  }
}
